package org.ak47.spring.boot.grpc.autoconfigure;


import io.grpc.BindableService;
import org.ak47.spring.boot.grpc.GrpcChannelsProperties;
import org.ak47.spring.boot.grpc.GrpcServerProperties;
import org.ak47.spring.boot.grpc.annotations.GrpcClient;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractApplicationContext;


/**
 * <p> GrpcAutoConfiguration </p>
 *
 * @author hexiaohong
 */
@Configuration
@ConditionalOnClass({GrpcChannelFactory.class})
@EnableConfigurationProperties({GrpcServerProperties.class, GrpcChannelsProperties.class})
@AutoConfigureAfter(BindableService.class)
public class GrpcAutoConfiguration
{
    private GrpcServerProperties grpcServerProperties;

    private GrpcChannelsProperties grpcChannelsProperties;

    public GrpcAutoConfiguration(GrpcServerProperties grpcServerProperties,
                                 GrpcChannelsProperties grpcChannelsProperties)
    {
        this.grpcServerProperties = grpcServerProperties;
        this.grpcChannelsProperties = grpcChannelsProperties;
    }

    @Bean
    public GrpcServerRunner grpcServerRunner(AbstractApplicationContext context)
    {
        return new GrpcServerRunner(context, grpcServerProperties,
                globalServerInterceptorRegistry());
    }

    @Bean
    public GlobalServerInterceptorRegistry globalServerInterceptorRegistry()
    {
        return new GlobalServerInterceptorRegistry();
    }

    @Bean
    public GlobalClientInterceptorRegistry globalClientInterceptorRegistry()
    {
        return new GlobalClientInterceptorRegistry();
    }

    @Bean
    @ConditionalOnMissingBean({GrpcChannelFactory.class})
    public GrpcChannelFactory defaultGrpcChannelFactory()
    {
        return new DefaultGrpcChannelFactory(grpcChannelsProperties,
            globalClientInterceptorRegistry());
    }

    @Bean
    @ConditionalOnClass({GrpcClient.class})
    public GrpcClientBeanPostProcessor grpcClientBeanPostProcessor()
    {
        return new GrpcClientBeanPostProcessor();
    }

}
